//
//  BaseWebViewController.swift
//  funcode
//
//  Created by Wan Jiading on 2017/4/21.
//  Copyright © 2017年 WanJiading. All rights reserved.
//

import UIKit
import WebKit

class BaseWebViewController: UIViewController, WKNavigationDelegate {

	var _wkWebView: WKWebView? = nil
	var webView: WKWebView? {
		get {
			if _wkWebView == nil {
				let screenWidth = UIScreen.main.bounds.size
				let frame = CGRect(x: 0, y: 64, width: screenWidth.width, height: screenWidth.height - 64 - 0)
				//				let webView = WKWebView(frame: frame, configuration: wkWebConfig)
				let webView = WKWebView(frame: frame)
				
				webView.navigationDelegate = self
				webView.isMultipleTouchEnabled = true
				webView.backgroundColor = UIColor.white
				//				webView.scrollView.delegate = self
				_wkWebView = webView
			}
			return _wkWebView
		}
		set (newValue) {
			_wkWebView = newValue
		}
	}
	
	
	/// 第一次打开当前页面
	var firstOpenPage = true
	
	/// url字符串，必须带访问协议 http://
	var urlString: String?
	
	// MARK: - 生命周期
	
	override func viewDidLoad() {
		super.viewDidLoad()
		
		self.view.backgroundColor = UIColor.white
		
		self.loadData()
	}
	
	// MARK: - 其他方法
	
	/// 加载数据方法
	
	private func getUrlString(_ urlString: String?) -> String {
		if (self.urlString != nil && self.urlString!.count > 0) {
			if (self.firstOpenPage) {
				return self.urlString!
			}
		} else {
			JDToast.show("urlString为空")
		}
		return ""
	}
	
	
	/// 设置 urlString
	///
	/// - Parameter urlString: 必须带访问协议，如：http://
	func resetUrlString(_ urlString: String?) {
		self.urlString = urlString
	}
	
	private func getRequest(_ urlString: String) -> URLRequest? {
		let urlStr = getUrlString(urlString)
		if (urlStr.count > 0) {
			if let url = URL(string: urlStr) {
				let request = URLRequest(url: url, cachePolicy: URLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 30.0)
				return request
			} else {
				JDToast.show("url转化失败")
			}
		}
		return nil
	}
	
	func loadData() {
		
		if (self.urlString == nil || self.urlString!.count == 0) {
			return
		}
		
		if (self.webView?.superview == nil) {
			self.view.addSubview(self.webView!)
		}
		
		if let request = getRequest(self.urlString!) {
			_ = self.webView?.load(request)
		}
	}
	
	
	// MARK: - WKNavigationDelegate
	
	/// 开始请求
	func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
		DebugLog("BaseWebViewController 开始请求")
		SharedApplication.isNetworkActivityIndicatorVisible = true
		JDProgressHUD.dismiss()
	}
	
	/// 拦截请求
	func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        DebugLog("BaseWebViewController \(String(describing: navigationAction.request.url?.absoluteString))")
		decisionHandler(.allow)
	}
	
	/// 加载完成
	func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
		DebugLog("BaseWebViewController 加载完毕")
		JDProgressHUD.dismiss()
		SharedApplication.isNetworkActivityIndicatorVisible = false
		webView.evaluateJavaScript("document.title") { [weak self] (result, error) in
			let title = result as! String
			if (title != "") {
				self?.navigationItem.title = title
			}
		}
	}
	
	/// 失败
	func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
		ErrorLog("BaseWebViewController 请求出错")
		ErrorLog("\(error)")
		SharedApplication.isNetworkActivityIndicatorVisible = false
		JDProgressHUD.dismiss()
	}
	
}
